package com.uva.pgpi.sgcc.web.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.uva.pgpi.sgcc.beans.Artefacto;
import com.uva.pgpi.sgcc.beans.Dependencia;
import com.uva.pgpi.sgcc.beans.Proyecto;
import com.uva.pgpi.sgcc.beans.Usuario;
import com.uva.pgpi.sgcc.util.DataBaseConnection;

/**
 * Servlet implementation class ServletArtefactos
 */
public class ServletArtefactos extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletArtefactos() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String idArtefacto = request.getParameter("id");
		if (idArtefacto != null && !idArtefacto.equals("")) {
			viewArtefacto(request, response);
		} else {
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(
							"/ServletRedir?redirigir=mainSolicitudes");
			dispatcher.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String htmlFormName = request.getParameter("htmlFormName");

		if (htmlFormName.equals("newArtefactoForm")) {
			this.newArtefacto(request, response);
		} else if (htmlFormName.equals("viewArtefacto")) {
			this.viewArtefacto(request, response);
		} else if (htmlFormName.equals("dependeArtefactoForm")) {
			this.setDependencias(request, response);
		}
	}

	private void setDependencias(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String idDep = (String) request.getParameter("idArtefacto");
		String idTarget1 = (String) request.getParameter("dependencyList_0");
		String idTarget2 = (String) request.getParameter("dependencyList_1");
	
		ConnectionSource cs = null;
		try {
			cs = DataBaseConnection.getInstance().getConnection();

			Dao<Dependencia, String> dependenciaDAO = DaoManager.createDao(cs,
					Dependencia.class);

			Dao<Artefacto, String> artefactoDAO = DaoManager.createDao(cs,
					Artefacto.class);

			
			Artefacto bean = artefactoDAO
			.queryForId(idDep);

			
			TableUtils.createTableIfNotExists(cs, Dependencia.class);
			
			if (idTarget1 != null && !idTarget1.equals("")) {
				dependenciaDAO.create(new Dependencia(bean, artefactoDAO
						.queryForId(idTarget1)));
			}
			if (idTarget2 != null && !idTarget2.equals("") && !idTarget2.equals(idTarget1)) {
				dependenciaDAO.create(new Dependencia(bean, artefactoDAO
						.queryForId(idTarget2)));
			}
			

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {

			if (cs != null && cs.isOpen()) {
				try {
					cs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/ServletRedir?redirigir=listaArtefactos");
			dispatcher.forward(request, response);
		}

	}

	private void newArtefacto(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Usuario user = (Usuario) request.getSession()
				.getAttribute("loggedUser");

		Artefacto bean = new Artefacto();

		ConnectionSource cs = null;
		try {
			cs = DataBaseConnection.getInstance().getConnection();
			Dao<Proyecto, String> proyectoDAO = DaoManager.createDao(cs,
					Proyecto.class);

			Dao<Artefacto, String> artefactoDAO = DaoManager.createDao(cs,
					Artefacto.class);

			if (user != null && user.getIdUsuario() > 0) {

				bean.setIdCreador(user);

				String p = (String) request.getParameter("proyectoList");

			 	bean.setNombre((String) request.getParameter("nombre"));
				bean.setDescripcion((String) request
						.getParameter("descripcion"));
				bean.setReferenciaFisica((String) request
						.getParameter("referenciaFisica"));

				bean.setProyecto(proyectoDAO.queryForId(p));

				artefactoDAO.createOrUpdate(bean);

			}

			request.setAttribute("artefactoSeleccionado", bean);
			request.setAttribute("id", bean.getIdArtefacto());

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {

			if (cs != null && cs.isOpen()) {
				try {
					cs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/WEB-INF/ccc/crearArtefacto2.jsp");
			dispatcher.forward(request, response);
		}

	}

	private void viewArtefacto(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ConnectionSource cs = null;
		try {
			cs = DataBaseConnection.getInstance().getConnection();
			Dao<Artefacto, String> artefactoDAO = DaoManager.createDao(cs,
					Artefacto.class);
			
			Dao<Dependencia, String> dependenciaDAO = DaoManager.createDao(cs,
					Dependencia.class);

			String idArtefacto = request.getParameter("id");
			Artefacto a = artefactoDAO.queryForId(idArtefacto);
			
			Iterator<Dependencia> it;
			
			it = dependenciaDAO.queryForEq(Dependencia.ID_DEPENDE_DE, idArtefacto).iterator();
			ArrayList<Artefacto> al = new ArrayList<Artefacto>();
			while(it.hasNext()){
				al.add(it.next().getTarget());
			}
			
			ArrayList<Artefacto> alC = new ArrayList<Artefacto>();
			it = dependenciaDAO.queryForEq(Dependencia.ID_TARGET, idArtefacto).iterator();
			while(it.hasNext()){
				alC.add(it.next().getDependeDe());
			}
			
			
			request.setAttribute("itDep", al.iterator());
			request.setAttribute("itDepCont", alC.iterator());

			if (a != null) {
				request.setAttribute("artefactoSeleccionado", a);
				request.setAttribute("id", a.getIdArtefacto());
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			
			if (cs != null && cs.isOpen()) {
				try {
					cs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

			
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/WEB-INF/ccc/verArtefacto.jsp");
			dispatcher.forward(request, response);
		}

	}

}
